﻿using MediatR;
using RedDragon.Common.Domain.Manufacture;
using RedDragon.Common.Dtos;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.API.Application.Commands.WorkCenter;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Resource
{
    public class QueryResourceHandler : IRequestHandler<QueryResourceCommand, Result<PageResultDto<Resources>>>
    {
        /// <summary>
        /// 工作表仓储
        /// </summary>
        public readonly IBaseRepository<Resources> resourcesRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<QueryResourceHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="resourcesRepository"></param>
        /// <param name="logger"></param>
        public QueryResourceHandler(IBaseRepository<Resources> resourcesRepository, ILogger<QueryResourceHandler> logger)
        {
            this.resourcesRepository = resourcesRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 资源列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<Resources>>> Handle(QueryResourceCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<Resources>>() { Code = (int)CommonErrorCode.Search };
            //实例化分页
            var page = new PageResultDto<Resources>() { TotalCount = 0, PageCount = 0, List = new List<Resources>() };
            try
            {
                //获取工作中心信息
                var list = await(await resourcesRepository.GetAll()).ToListAsync();
                //当工作编号存在的时候进行查询
                if (!string.IsNullOrEmpty(request.WorkCenterCode)) 
                {
                    list=list.Where(d => d.WorkCenterCode == request.WorkCenterCode).ToList();
                }
                //总条数
                page.TotalCount = list.Count();
                page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.PageSize);
                page.List = list.OrderBy(d => d.ResourceId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Data = page;
                result.Code = (int)CommonErrorCode.Success;
                result.Msg = "获取资源列表成功";
            }
            catch (Exception ex)
            {
                result.Msg = "获取资源列表异常" + ex.Message;
                logger.LogError("获取资源列表异常" + ex.Message);
            }
            return result;
        }
    }
}
